package com.sf.fy.uav.applet.operate.controller;

import com.sf.fy.uav.common.request.operate.FileAddRequest;
import com.sf.fy.uav.common.response.operational.BusinessLicenseResponse;
import com.sf.fy.uav.common.utils.OcrUtil;
import com.sf.fy.uav.common.utils.Rs;
import com.sf.fy.uav.common.utils.UploadToOssUtils;
import com.sf.fy.uav.controller.FileRest;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;


/**
 * @author LTQ
 */
@RestController
@RequestMapping("/home/file/")
@Tag(name = "file管理")
public class SysFileController {

    @Autowired
    private UploadToOssUtils uploadToOssUtils;

    @Autowired
    private FileRest fileRest;

    private final static Logger logger = LoggerFactory.getLogger(SysFileController.class);


    @Value("${oss.public-path:https://sit-ie-uocs-core-shenzhen-xili1-oss.sit.sf-express.com/v1.2/AUTH_sit-IE-UOCS-CORE/sfosspublic001}")
    private String ossPublicPath;

    @Autowired
    private OcrUtil ocrUtil;


    @PostMapping("picture")
    @CrossOrigin
    @Parameter(name = "subject", description = "取值含义businessLicense上传营业执照图片")
    public Rs<BusinessLicenseResponse> uploadPicture(HttpServletRequest request, HttpServletResponse response, @RequestParam String subject, @RequestParam(required = false) String compressionQuality) throws Exception {
        FileAddRequest fileAddRequest = uploadToOssUtils.uploadPicture(request, response, subject, compressionQuality);
        BusinessLicenseResponse businessLicenseResponse = new BusinessLicenseResponse();
        com.sf.fy.uav.entity.File file2 = fileRest.add(fileAddRequest);
        businessLicenseResponse.setFileId(file2.getId());
        businessLicenseResponse.setFilePath(fileAddRequest.getFilePath());
        logger.info("fileAddRequest:{}", fileAddRequest);
        logger.info("filePath:{}", ossPublicPath + fileAddRequest.getFilePath());
        String ocrString = ocrUtil.ocr(ossPublicPath + fileAddRequest.getFilePath());
        logger.info("ocrString:{}", ocrString);
        businessLicenseResponse.setOcrString(ocrString);
        return Rs.success(businessLicenseResponse);
    }


    @GetMapping("download")
    @Operation(tags = "下载批量下单模板", description = "下载批量下单模板")
    @Parameter(name = "subject", description = "取值含义batchPlaceOrderTemplate下载批量上传模板，printInstructions下载打印说明", required = true)
    public void download(HttpServletResponse response, @RequestParam String subject) {
        // 下载网络文件
        String dirPath = "";
        if (subject.equals("batchPlaceOrderTemplate")) {
            dirPath += "/applet/batchPlaceOrderTemplate/batch_place_order.xlsx";
        } else if (subject.equals("printInstructions")) {
            dirPath += "/applet/printInstructions/printInstructions.docx";
        }
        URL url;
        try {
            url = new URL(ossPublicPath + dirPath);
        } catch (MalformedURLException e) {
            throw new RuntimeException(e);
        }
        try {
            URLConnection conn = url.openConnection();
            InputStream inputStream = conn.getInputStream();
            byte[] buffer = new byte[inputStream.available()];

            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=批量下单模板");
            OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            outputStream.close();
            inputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
